package com.quiz.bis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.quiz.bis.domain.bo.InviteCreateBo;
import com.quiz.bis.domain.model.ExamGroup;
import com.quiz.bis.domain.model.ExamGroupInvite;
import com.quiz.bis.mapper.ExamGroupInviteMapper;
import com.quiz.bis.mapper.ExamGroupMapper;
import com.quiz.bis.service.IExamGroupInviteService;
import com.quiz.common.core.domain.R;
import com.quiz.common.mybatis.core.page.PageQuery;
import com.quiz.common.mybatis.core.page.TableDataInfo;
import com.quiz.common.mybatis.core.query.PlusWrappers;
import com.quiz.common.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;

@Service
@RequiredArgsConstructor
public class ExamGroupInviteServiceImpl implements IExamGroupInviteService {
    private final ExamGroupInviteMapper inviteMapper;
    private final ExamGroupMapper groupMapper;

    @Override
    @Transactional
    public R<ExamGroupInvite> createInvite(InviteCreateBo bo) {
        Long userId = SecurityUtils.getUserId();

        // 验证考试组和权限
        ExamGroup group = groupMapper.selectById(bo.getGroupId());
        if (group == null || !group.getMainOwnerId().equals(userId)) {
            return R.fail("无权操作该考试组");
        }

        // 生成唯一邀请码
        String code = generateInviteCode();

        ExamGroupInvite invite = new ExamGroupInvite();
        invite.setGroupId(bo.getGroupId());
        invite.setCode(code);
        invite.setType(bo.getType());
        invite.setMaxUses(bo.getMaxUses());
        invite.setUsedCount(0);
        invite.setExpireTime(bo.getExpireTime());
        invite.setCreateBy(userId.toString());
        invite.setDeptId(SecurityUtils.getDeptId());


        inviteMapper.insert(invite);
        return R.ok(invite);
    }

    @Override
    public TableDataInfo<ExamGroupInvite> getInvites(Long groupId, String keyword, Integer type, PageQuery pageQuery) {
        Page<ExamGroupInvite> page = inviteMapper.selectPage(
                pageQuery.build(),
                PlusWrappers.lambdaQuery(ExamGroupInvite.class)
                        .eq(ExamGroupInvite::getGroupId, groupId)
                        .eq(ExamGroupInvite::getDelFlag, 0)
                        .eqIfPresent(ExamGroupInvite::getType, type)
                        .likeIfPresent(ExamGroupInvite::getCode, keyword)
                        .orderByDesc(ExamGroupInvite::getCreateTime)
        );
        return TableDataInfo.build(page);
    }

    @Override
    public R<Void> deleteInvite(Long id) {
        inviteMapper.deleteById(id);
        return R.ok();
    }

    // 生成8位随机字母数字混合码
    private String generateInviteCode() {
        String chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
        StringBuilder sb = new StringBuilder();
        Random random = new Random();

        for (int i = 0; i < 8; i++) {
            sb.append(chars.charAt(random.nextInt(chars.length())));
        }

        // 检查是否已存在
        if (inviteMapper.exists(new LambdaQueryWrapper<ExamGroupInvite>()
                .eq(ExamGroupInvite::getCode, sb.toString()))) {
            return generateInviteCode(); // 递归直到生成唯一码
        }

        return sb.toString();
    }
}
